package com.snow.java.base.junit;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * @类名称：
 * @类描述：
 * @author: bingHeng
 * @Date 2019.04.05
 * @Version: 1.0
*/
public class MyLambad2 {
    /**
     * Java8内置的四大核心函数式接口
     *
     * Consumer<T>: 消费型接口
     *  void accept(T t);
     *
     * Supplier<T>: 供给型接口
     *  T get();
     *
     * Function<T, R>: 函数型接口
     *  R apply(T, t);
     *
     * Predicate<T>:断言型接口
     *  boolean test(T t);
     */

    public static void main(String[] args) {
        happey(10000.00, (m) -> System.out.println("今天出去逛超市花了" + m + "元整！"));
        List<Integer> numList = getNumList(20, () -> (int) (Math.random() * 100));
        System.out.println(numList);
        String result = strHandler("你是我的小苹果", (m) -> m.substring(5, 7));
        System.out.println(result);

        System.out.println("-----------------------------------------------------------------");
        List<String> list = Arrays.asList("Hello", "Lambda", "com", "www", "isOk");

        List<String> resultList = filterStr(list, (m) -> m.length() > 3);
        System.out.println(resultList);
    }


    // Consumer<T>
    public static void happey(double money, Consumer<Double> consumer) {
        consumer.accept(money);
    }

    // Supplier 产生一些整数，并放入集合中
    public static List<Integer> getNumList(int num, Supplier<Integer> supplier) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            list.add(supplier.get());
        }
        return list;
    }

    // Function<T, R>  传入一个字符串，返回一个字符串
    public static String strHandler(String str, Function<String, String> fun) {
        return fun.apply(str);
    }

    // Predicate<T>
    public static List<String> filterStr(List<String> list, Predicate<String> predicate) {
        List<String> resultList = new ArrayList<>();
        for(String str : list) {
            if(predicate.test(str)) {
                resultList.add(str);
            }
        }
        return resultList;
    }

    // java 8中更多内置接口请自行参考API
}
